<?php
namespace App\Console\Commands;

use App\Models\AddressBookBinding;
use App\Models\MessagesSent;
use App\Models\MessagesSentFailure;
use App\Models\MessagesSentSucceed;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Schema;

class send_message extends Command {

    /**
     * @var 设置执行的命令
     */
    protected $signature  = 'send_message:send {action}';

    protected $msg_id = 1;


    /**
     * The console command description.
     *
     * @var string
     */

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        // 获取参数，调用方法
        $action = $this->argument('action');
        $this->$action();
    }

    public function sync()
    {
        $list = MessagesSentFailure::where([['id', '>', 1463]])->limit(2000)->get();
        $batch_mobile = [];
        foreach($list as $mobile){
            $batch_mobile[] = ['msg_id' => $this->msg_id, 'msg_type' => 0, 'mobile' => $mobile->mobile, 'created_at' => time(), 'remark' => '群发短信已发送成功'];
        }
        if(!empty($batch_mobile))
            MessagesSentSucceed::insert($batch_mobile);
        dd('同步完成');
    }

    /*
     * 创建需要发送的用户
     * */
    public function send_user()
    {
        $key = 'send_message_upgrade';

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 获取所有注册用户
        $userList = User::select(['mobile'])->where([['mobile', '!=', '']])->orderBy('id', 'asc')->get();
        $i = 0;
        $i_err = 0;
        $cf_ii = 0;

        foreach ($userList as $value){
            if (!preg_match('/^(\+86(\-)?)?1[345789]\d{9}$/', str_replace(' ', '', $value->mobile))) {
                $i_err++;
                Redis::lpush($key.'_fail', $value->mobile);
                continue;
            }

            $is_record = MessagesSentSucceed::select(['id'])->where(['msg_id' =>$this->msg_id, 'msg_type' => 0, 'mobile' => $value->mobile])->first();
            if(!empty($is_record)){
                $cf_ii++;
                continue;
            }

            Redis::zadd($key, [$value->mobile=>$value->mobile]);
            $i++;
        }
        echo '---------------------------------注册用户：有效数量：'.$i.' && 无效数量： '.$i_err.' && 过滤重复：'.$cf_ii.'---------------------------------';
        echo "\r\n\r\n";
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 获取通讯录绑定
        $addressBookList = AddressBookBinding::select('addrss_book_mobile')->get();
        $i = 0;
        $cf_ii = 0;
        $i_err = 0;
        foreach ($addressBookList as $avalue){

            if(!empty($avalue->addrss_book_mobile)){
                // 分割通讯录 -- 遍历
                $a_temp_arr = explode(',', $avalue->addrss_book_mobile);
                foreach ($a_temp_arr as $at_value){
                    if(!empty(trim($at_value))){
                        if (!preg_match('/^(\+86(\-)?)?1[345789]\d{9}$/', str_replace(' ', '', $at_value))) {
                            $i_err++;
                            continue;
                        }

                        // 配置的id  校验数据是否存在
                        $is_record = MessagesSentSucceed::select(['id'])->where(['msg_id' => $this->msg_id, 'msg_type' => 0, 'mobile' => $at_value])->first();
                        if(!empty($is_record)){
                            $cf_ii++;
                            continue;
                        }

                        Redis::zadd($key, [$at_value=>$at_value]);
                        $i++;
                    }
                }
            }
        }
        echo '---------------------------------通讯录用户：有效数量：'.$i.' -- 无效数量： '.$i_err.' && 过滤重复：'.$cf_ii.'---------------------------------';
        echo "\r\n\r\n";
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }

    /*
     * 对用户发送短信
     * */
    public function send_message_upgrade()
    {

        $key = 'send_message_upgrade';

        $rs = MessagesSent::where(['id' => $this->msg_id, 'status' => 1])->first();
        if(!$rs)
            return false;
        $content = $rs->content;

        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // 发送短信
        $count = Redis::zcard($key);

        //每100条一个批次
        $pagesize = 100;
        $end_pagesize = 400;//$count%$pagesize+$pagesize;
        $total_page = (int)ceil($count/$end_pagesize);

        $j = 0;
        $j_err = 0;
        for($ii=0;$ii<$total_page;$ii++){
            // 取出第一页  -- 发送短信
            $list = Redis::zrange($key, 0, ($end_pagesize-1));

            if(!empty($list)){
                $send_message = send_group_msg(implode(',', $list), $content);

                // 删除成功  -- 删除
                if(!empty($list) && $send_message == true) {
                    $j = $j + count($list);
                    $del = Redis::zrem($key, $list);

                    $batch_mobile = [];
                    foreach($list as $mobile)
                        $batch_mobile[] = ['msg_id' => $this->msg_id, 'msg_type' => 0, 'mobile' => $mobile, 'created_at' => time(), 'remark' => '群发短信已发送成功'];
                    if(!empty($batch_mobile))
                        MessagesSentSucceed::insert($batch_mobile);

                }else{
                    $j_err = $j_err + count($list);
                    // 记录发送失败的手机号
                    foreach ($list as $v)
                        Redis::lpush($key.':error', $v);

                    $failure_mobile_list = [];
                    foreach($list as $mobile)
                        $failure_mobile_list[] = ['msg_id' => $this->msg_id, 'msg_type' => 0, 'mobile' => $mobile, 'created_at' => time(), 'remark' => '群发短信已发送失败'];
                    if(!empty($failure_mobile_list))
                        MessagesSentFailure::insert($failure_mobile_list);

                }
            }
        }

        echo '---------------------------------已发送：'.$j.'---------------------------------';
        echo "\r\n";
        echo '---------------------------------未发送：'.$j_err.'---------------------------------';
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }

}